<%= stylesheet_link_tag 'components/_tree' %>

<script type="text/javascript" charset="utf-8">
    $(function () {
        var detailTree = root.getWidgetById("detail-tree"),
            frame = $("iframe#one_frame"),
            mp, // 播放器实例
            startTime = 0, // 已播放时长, 默认0
            duration = 300, // 总时长, 默认5分钟
            halfDuration;

        // 小窗加载之后, 给mp赋值
        frame.load(function () {
            <% unless Rails.env.development? %>
            if (STBType.indexOf("EC2106") >= 0 || STBType === "EC6110T_sp30_hbedx") {
                var frameContent = frame.contentWindow || frame.contentDocument;
                mp = frameContent.mp;
            } else {
                mp = new MediaPlayer(); // 创建播放器实例
                var instanceId = mp.getNativePlayerInstanceID();
                mp.bindNativePlayerInstance(instanceId);
            }
            <% end %>
        });

        var updateProgress = function () {
            // 某些盒子不能触发768, 并且播放到最末尾会卡住, 最后已播放时间变为0, duration为0, 需要手动切歌; 要与能触发768的盒子做个兼容
            // 某些视频播放到末尾也会变成已播放时间变为0, duration为0; 此时会造成两次切换下一曲, 要做兼容
            interval = setInterval(function () {
                <% unless Rails.env.development? %>
                startTime = mp.getCurrentPlayTime();
                duration = mp.getMediaDuration();
                if (duration > 0) {
                    halfDuration = duration / 2;
                }
                <% end %>

                // TODO: 不能用三个等于, 两个等于就是好的, 这里好像不是number类型
                if (halfDuration > 0 && (startTime == duration - 1)) {
                    clearInterval(interval)
                    halfDuration = 0
                    playNext();
                }
            }, 1000);
        };

        function selectSelf(frame, dataset) {
            <% if current_page?('/search') %>
            window.location.href = "<%= fullscreen_play_path(play_type: "once", second_prev: request.fullpath).html_safe %>" + "&song_id=" + dataset.id;
            <% else %>
            // 修改短视频的src, 开启播放, 重置计数器
            changeMediaSrc(dataset.content_id);
            resetCount();

            frame.attr("data-song_id", dataset.id)
            <% if current_page?(mine_song_fav_path) %>
            frame.attr("data-href", "<%= fullscreen_play_path(play_type: 'song_fav_bunch', second_prev: request.fullpath).html_safe %>" + "&song_id=" + dataset.id);
            <% elsif current_page?(mine_picklist_path)%>
            frame.attr("data-href", "<%= fullscreen_play_path(play_type: 'picklist_bunch', second_prev: request.fullpath).html_safe %>" + "&song_id=" + dataset.id);
            <% elsif current_page?(mine_history_path)%>
            frame.attr("data-href", "<%= fullscreen_play_path(play_type: 'history_bunch', second_prev: request.fullpath).html_safe %>" + "&song_id=" + dataset.id);
            <% elsif current_page?(playlist_path(params[:id] ||= 1)) %>
            frame.attr("data-href", "<%= fullscreen_play_path(play_type: 'playlist_bunch', id: params[:id] ||= 1, second_prev: request.fullpath).html_safe %>" + "&song_id=" + dataset.id);
            <% elsif current_page?(singer_path(params[:id] ||= 1)) %>
            frame.attr("data-href", "<%= fullscreen_play_path(play_type: 'singer_bunch', id: params[:id] ||= 1, second_prev: request.fullpath).html_safe %>" + "&song_id=" + dataset.id);
            <% end %>
            <% end %>
        }

        <% unless current_page?('/search') %>
        // 使用第一首歌曲, 对播放器做初始化
        var targetSong = detailTree.getFocusedLeaf();
        selectSelf(frame, targetSong.con.dataset);
        updateProgress();
        <% end %>

        // 播放下一首
        var playNext = function () {
            var currentFocus = detailTree.getFocusedChildWidget();
            var index = parseInt(currentFocus.id.split("song")[1]);

            var next;
            // 歌曲列表的数量
            if (index === $(".detail-item-song").length - 1) {
                next = 0;
            } else {
                next = index + 1;
            }
            targetSong = FocusEngine.getWidgetById("song" + next).focus();
            selectSelf(frame, targetSong.con.dataset);
            updateProgress()
        };

        detailTree.on("keydown", function (e) {
            e = e || window.event;
            var keyValue = e.which || e.keyCode;
            if (keyValue === 13) {
                var con = e.target.con;
                var dataset = con.dataset;

                switch (String(dataset.kind)) {
                    case "song":
                        selectSelf(frame, dataset);
                        break;
                    case "pick":
                        // 选中绿色减号, 未选中白色加号
                        var pickImg = $(con).children();
                        $.ajax({
                            url: "<%= users_toggle_pick_path %>" + "?id=" + dataset.id,
                            dataType: "text",
                            type: "POST",
                            success: function (data) {
                                if (data === "create") {
                                    pickImg.removeClass("white-plus").addClass("green-minus");
                                } else {
                                    pickImg.removeClass("green-minus").addClass("white-plus");
                                }
                            }
                        }).done(function () {
                            FocusEngine.render(); // 重新渲染组件树
                        });
                        break;
                    case "fav":
                        // 选中绿色爱心, 未选中白色爱心
                        var favImg = $(con).children();
                        $.ajax({
                            url: "<%= users_toggle_fav_path %>" + "?id=" + dataset.id,
                            dataType: "text",
                            type: "POST",
                            success: function (data) {
                                if (data === "create") {
                                    favImg.removeClass("white-fav").addClass("green-fav");
                                } else {
                                    favImg.removeClass("green-fav").addClass("white-fav");
                                }
                            }
                        }).done(function () {
                            FocusEngine.render(); // 重新渲染组件树
                        });
                        break;
                    default:
                        break;
                }
            }
        });

        detailTree.on("focus", function (e) {
            $(e.target.con).find(".marquee-truncate").marquee().trigger("forward").off("forward");
        });

        detailTree.on("blur", function (e) {
            $(e.target.con).find(".marquee-truncate").trigger("reset").off("reset");
        });
    });
</script>

<div class="detail">
  <div id="detail-tree" class="detail-tree fe-cache" fe-role="Scroll"
       fe-cfg="default_focus:yes,scroll_dir:v,scroll_duration:0.3,scroll_easing:ease-out">

    <div class="scroll-list">
      <div id="tree-wrapper">
        <%= render "shared/tree_wrapper", items: items %>
      </div>
    </div>

  </div>

  <div class="detail-pager">
    共 <span id="detail-pager-text"><%= items.size %></span> 首
  </div>
</div>
